package com.egg.gateway.filter;

import com.egg.common.util.IpUtil;
import com.egg.gateway.config.BlackConfig;
import com.egg.gateway.constant.FilterOrderConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 黑名单拦截
 *
 * @author east
 */
@Slf4j
@Component
public class BlackFilter implements GlobalFilter, Ordered {


    @Autowired
    private BlackConfig blackConfig;


    @Override
    public int getOrder() {
        return FilterOrderConstant.BLACK_FILTER_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (blackConfig.isBlackIp(IpUtil.requestIp(request))) {
            // 在黑名单中, 返回认证失败.
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }


}